{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# vrptw_store_solution_data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/vrptw_store_solution_data.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/vrptw_store_solution_data.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "VRPTW example that stores routes and cumulative data in an array.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ortools.constraint_solver import routing_enums_pb2\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "\n",
    "def create_data_model():\n",
    "    \"\"\"Stores the data for the problem.\"\"\"\n",
    "    data = {}\n",
    "    data[\"time_matrix\"] = [\n",
    "        [0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7],\n",
    "        [6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14],\n",
    "        [9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9],\n",
    "        [8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16],\n",
    "        [7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14],\n",
    "        [3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8],\n",
    "        [6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5],\n",
    "        [2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10],\n",
    "        [3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6],\n",
    "        [2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5],\n",
    "        [6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4],\n",
    "        [6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10],\n",
    "        [4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8],\n",
    "        [4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6],\n",
    "        [5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2],\n",
    "        [9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9],\n",
    "        [7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0],\n",
    "    ]\n",
    "    data[\"time_windows\"] = [\n",
    "        (0, 5),  # depot\n",
    "        (7, 12),  # 1\n",
    "        (10, 15),  # 2\n",
    "        (16, 18),  # 3\n",
    "        (10, 13),  # 4\n",
    "        (0, 5),  # 5\n",
    "        (5, 10),  # 6\n",
    "        (0, 4),  # 7\n",
    "        (5, 10),  # 8\n",
    "        (0, 3),  # 9\n",
    "        (10, 16),  # 10\n",
    "        (10, 15),  # 11\n",
    "        (0, 5),  # 12\n",
    "        (5, 10),  # 13\n",
    "        (7, 8),  # 14\n",
    "        (10, 15),  # 15\n",
    "        (11, 15),  # 16\n",
    "    ]\n",
    "    data[\"num_vehicles\"] = 4\n",
    "    data[\"depot\"] = 0\n",
    "    return data\n",
    "\n",
    "\n",
    "\n",
    "def print_solution(routes, cumul_data):\n",
    "    \"\"\"Print the solution.\"\"\"\n",
    "    total_time = 0\n",
    "    route_str = \"\"\n",
    "    for i, route in enumerate(routes):\n",
    "        if len(route) <= 2:\n",
    "            continue\n",
    "        route_str += \"Route \" + str(i) + \":\\n\"\n",
    "        start_time = cumul_data[i][0][0]\n",
    "        end_time = cumul_data[i][0][1]\n",
    "        route_str += (\n",
    "            \"  \"\n",
    "            + str(route[0])\n",
    "            + \" Time(\"\n",
    "            + str(start_time)\n",
    "            + \", \"\n",
    "            + str(end_time)\n",
    "            + \")\"\n",
    "        )\n",
    "        for j in range(1, len(route)):\n",
    "            start_time = cumul_data[i][j][0]\n",
    "            end_time = cumul_data[i][j][1]\n",
    "            route_str += (\n",
    "                \" -> \"\n",
    "                + str(route[j])\n",
    "                + \" Time(\"\n",
    "                + str(start_time)\n",
    "                + \", \"\n",
    "                + str(end_time)\n",
    "                + \")\"\n",
    "            )\n",
    "        route_str += f\"\\n  Route time: {start_time}min\\n\\n\"\n",
    "        total_time += cumul_data[i][len(route) - 1][0]\n",
    "    route_str += f\"Total time: {total_time}min\"\n",
    "    print(route_str)\n",
    "\n",
    "\n",
    "\n",
    "def get_routes(solution, routing, manager):\n",
    "    \"\"\"Get vehicle routes from a solution and store them in an array.\"\"\"\n",
    "    # Get vehicle routes and store them in a two dimensional array whose\n",
    "    # i,j entry is the jth location visited by vehicle i along its route.\n",
    "    routes = []\n",
    "    for route_nbr in range(routing.vehicles()):\n",
    "        index = routing.Start(route_nbr)\n",
    "        route = [manager.IndexToNode(index)]\n",
    "        while not routing.IsEnd(index):\n",
    "            index = solution.Value(routing.NextVar(index))\n",
    "            route.append(manager.IndexToNode(index))\n",
    "        routes.append(route)\n",
    "    return routes\n",
    "\n",
    "\n",
    "\n",
    "def get_cumul_data(solution, routing, dimension):\n",
    "    \"\"\"Get cumulative data from a dimension and store it in an array.\"\"\"\n",
    "    # Returns an array cumul_data whose i,j entry contains the minimum and\n",
    "    # maximum of CumulVar for the dimension at the jth node on route :\n",
    "    # - cumul_data[i][j][0] is the minimum.\n",
    "    # - cumul_data[i][j][1] is the maximum.\n",
    "\n",
    "    cumul_data = []\n",
    "    for route_nbr in range(routing.vehicles()):\n",
    "        route_data = []\n",
    "        index = routing.Start(route_nbr)\n",
    "        dim_var = dimension.CumulVar(index)\n",
    "        route_data.append([solution.Min(dim_var), solution.Max(dim_var)])\n",
    "        while not routing.IsEnd(index):\n",
    "            index = solution.Value(routing.NextVar(index))\n",
    "            dim_var = dimension.CumulVar(index)\n",
    "            route_data.append([solution.Min(dim_var), solution.Max(dim_var)])\n",
    "        cumul_data.append(route_data)\n",
    "    return cumul_data\n",
    "\n",
    "\n",
    "\n",
    "def main():\n",
    "    \"\"\"Solve the VRP with time windows.\"\"\"\n",
    "    # Instantiate the data problem.\n",
    "    data = create_data_model()\n",
    "\n",
    "    # Create the routing index manager.\n",
    "    manager = pywrapcp.RoutingIndexManager(\n",
    "        len(data[\"time_matrix\"]), data[\"num_vehicles\"], data[\"depot\"]\n",
    "    )\n",
    "\n",
    "    # Create Routing Model.\n",
    "    routing = pywrapcp.RoutingModel(manager)\n",
    "\n",
    "    # Create and register a transit callback.\n",
    "    def time_callback(from_index, to_index):\n",
    "        \"\"\"Returns the travel time between the two nodes.\"\"\"\n",
    "        # Convert from routing variable Index to time matrix NodeIndex.\n",
    "        from_node = manager.IndexToNode(from_index)\n",
    "        to_node = manager.IndexToNode(to_index)\n",
    "        return data[\"time_matrix\"][from_node][to_node]\n",
    "\n",
    "    transit_callback_index = routing.RegisterTransitCallback(time_callback)\n",
    "\n",
    "    # Define cost of each arc.\n",
    "    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
    "\n",
    "    # Add Time Windows constraint.\n",
    "    time = \"Time\"\n",
    "\n",
    "    routing.AddDimension(\n",
    "        transit_callback_index,\n",
    "        30,  # allow waiting time\n",
    "        30,  # maximum time per vehicle\n",
    "        False,  # Don't force cumulative time to be 0 at start of routes.\n",
    "        time,\n",
    "    )\n",
    "    time_dimension = routing.GetDimensionOrDie(time)\n",
    "    # Add time window constraints for each location except depot.\n",
    "    for location_idx, time_window in enumerate(data[\"time_windows\"]):\n",
    "        if location_idx == 0:\n",
    "            continue\n",
    "        index = manager.NodeToIndex(location_idx)\n",
    "        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])\n",
    "    # Add time window constraints for each vehicle start node.\n",
    "    for vehicle_id in range(data[\"num_vehicles\"]):\n",
    "        index = routing.Start(vehicle_id)\n",
    "        time_dimension.CumulVar(index).SetRange(\n",
    "            data[\"time_windows\"][0][0], data[\"time_windows\"][0][1]\n",
    "        )\n",
    "\n",
    "    # Instantiate route start and end times to produce feasible times.\n",
    "    for i in range(data[\"num_vehicles\"]):\n",
    "        routing.AddVariableMinimizedByFinalizer(\n",
    "            time_dimension.CumulVar(routing.Start(i))\n",
    "        )\n",
    "        routing.AddVariableMinimizedByFinalizer(time_dimension.CumulVar(routing.End(i)))\n",
    "\n",
    "    # Setting first solution heuristic.\n",
    "    search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
    "    search_parameters.first_solution_strategy = (\n",
    "        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC\n",
    "    )\n",
    "\n",
    "    # Solve the problem.\n",
    "    solution = routing.SolveWithParameters(search_parameters)\n",
    "\n",
    "    # Print solution.\n",
    "    if solution:\n",
    "        routes = get_routes(solution, routing, manager)\n",
    "        cumul_data = get_cumul_data(solution, routing, time_dimension)\n",
    "        print_solution(routes, cumul_data)\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
